"""
TTS工具打包脚本
使用PyInstaller将tts.py打包成Windows可执行文件
"""

import os
import sys
import shutil
import subprocess
from pathlib import Path

def check_requirements():
    """检查必要的依赖"""
    required_packages = ['pyinstaller', 'edge-tts', 'ttkbootstrap', 'pygame']
    missing_packages = []
    
    for package in required_packages:
        try:
            __import__(package.replace('-', '_'))
        except ImportError:
            missing_packages.append(package)
    
    if missing_packages:
        print(f"缺少以下包：{', '.join(missing_packages)}")
        print("正在安装缺失的包...")
        for package in missing_packages:
            subprocess.check_call([sys.executable, "-m", "pip", "install", package])
        print("依赖安装完成！")

def build_exe():
    """构建exe文件"""
    print("开始打包TTS工具...")
    
    # PyInstaller命令参数
    cmd = [
        "pyinstaller",
        "--noconfirm",  # 覆盖输出目录
        "--onefile",    # 打包成单个文件
        "--windowed",   # 不显示控制台窗口
        "--name", "文字转语音工具",  # 输出文件名
        "--icon", "img/wzy.ico",  # 使用自定义图标
        "--add-data", f"{sys.prefix}/Lib/site-packages/ttkbootstrap;ttkbootstrap",  # 包含ttkbootstrap资源
        "--hidden-import", "ttkbootstrap",
        "--hidden-import", "edge_tts",
        "--hidden-import", "pygame",
        "--hidden-import", "asyncio",
        "--hidden-import", "concurrent.futures",
        "--hidden-import", "multiprocessing",
        "--hidden-import", "multiprocessing.spawn",
        "--hidden-import", "multiprocessing.freeze_support",
        "--collect-all", "ttkbootstrap",  # 收集ttkbootstrap的所有文件
        "--collect-all", "edge_tts",      # 收集edge_tts的所有文件
        "tts.py"
    ]
    
    try:
        subprocess.run(cmd, check=True)
        print("\n✅ 打包成功！")
        print(f"可执行文件位置：dist/文字转语音工具.exe")
        
        # 复制README到dist目录
        if Path("README.md").exists():
            shutil.copy("README.md", "dist/使用说明.md")
            print("已复制使用说明到dist目录")
            
    except subprocess.CalledProcessError as e:
        print(f"\n❌ 打包失败：{e}")
        return False
    
    return True

def create_spec_file():
    """创建自定义spec文件（可选）"""
    spec_content = """
# -*- mode: python ; coding: utf-8 -*-

block_cipher = None

a = Analysis(
    ['tts.py'],
    pathex=[],
    binaries=[],
    datas=[],
    hiddenimports=[
        'ttkbootstrap',
        'edge_tts',
        'pygame',
        'asyncio',
        'concurrent.futures',
        'multiprocessing',
        'multiprocessing.spawn',
        'multiprocessing.freeze_support',
        'tkinter',
        'tkinter.ttk'
    ],
    hookspath=[],
    hooksconfig={},
    runtime_hooks=[],
    excludes=[],
    win_no_prefer_redirects=False,
    win_private_assemblies=False,
    cipher=block_cipher,
    noarchive=False,
)

pyz = PYZ(a.pure, a.zipped_data, cipher=block_cipher)

exe = EXE(
    pyz,
    a.scripts,
    a.binaries,
    a.zipfiles,
    a.datas,
    [],
    name='文字转语音工具',
    debug=False,
    bootloader_ignore_signals=False,
    strip=False,
    upx=True,
    upx_exclude=[],
    runtime_tmpdir=None,
    console=False,  # False表示不显示控制台
    disable_windowed_traceback=False,
    argv_emulation=False,
    target_arch=None,
    codesign_identity=None,
    entitlements_file=None,
    icon='img/wzy.ico',  # 使用自定义图标
)
"""
    
    with open("tts.spec", "w", encoding="utf-8") as f:
        f.write(spec_content)
    print("已创建自定义spec文件")

def main():
    """主函数"""
    print("=" * 50)
    print("TTS工具打包脚本")
    print("=" * 50)
    
    # 检查当前目录
    if not Path("tts.py").exists():
        print("错误：当前目录下没有找到tts.py文件")
        print("请在tts目录下运行此脚本")
        return
    
    # 检查并安装依赖
    check_requirements()
    
    # 开始打包
    if build_exe():
        print("\n" + "=" * 50)
        print("打包完成！")
        print("可执行文件：dist/文字转语音工具.exe")
        print("使用说明：dist/使用说明.md")
        print("=" * 50)
    else:
        print("\n打包过程中出现错误，请检查错误信息")

if __name__ == "__main__":
    main()
